import { ref, computed } from 'vue'
import dayjs from 'dayjs'

export interface RecordTimeOptions {
  startTime?: string // YYYY-MM-DD HH:mm:ss
  duration?: number // 初始持续时间(秒)
}

const dateFormat = "YYYY-MM-DD HH:mm:ss";

export function useRecordTime() {
  const startTime = ref<dayjs.Dayjs | null>(null) // 开始时间
  const beforeTotalDuration = ref(0) // 暂停前累计时长(秒)
  const currentDuration = ref(0) // 当前总时长(秒)
  const isRecording = ref(false) // 录制状态
  let timer: ReturnType<typeof setInterval> | null = null

  // 格式化持续时间为 HH:mm:ss
  const formattedDuration = computed(() => {
    const hours = Math.floor(currentDuration.value / 3600)
    const minutes = Math.floor((currentDuration.value % 3600) / 60)
    const seconds = currentDuration.value % 60
    
    const hoursStr = hours > 0 ? `${String(hours).padStart(2, '0')}:` : ''
    return `${hoursStr}${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`
  })

  // 获取当前录制时长
  const getCurrentDuration = () => {
    if (isRecording.value && startTime.value) {
      const now = dayjs()
      currentDuration.value = beforeTotalDuration.value + 
        Math.floor(now.diff(startTime.value) / 1000)
      return currentDuration.value
    }
    currentDuration.value = beforeTotalDuration.value
    return currentDuration.value
  }

  // 设置开始时间
  const setStartTime = (timeStr: string) => {
    startTime.value = dayjs(timeStr, dateFormat);
  }

  const setDuration = (duration: number) => {
    beforeTotalDuration.value = duration
  }

  // 开始计时
  const start = () => {
    if (isRecording.value) return
    
    startTime.value = dayjs()
    isRecording.value = true
    
    timer = setInterval(() => {
      getCurrentDuration()
    }, 1000)
  }

  // 暂停计时
  const pause = () => {
    if (!isRecording.value) return
    
    beforeTotalDuration.value = getCurrentDuration()
    startTime.value = null
    isRecording.value = false
    
    if (timer) {
      clearInterval(timer)
      timer = null
    }
  }

  // 恢复计时
  const resume = () => {
    if (isRecording.value) return
    start()
  }

  // 停止计时
  const stop = () => {
    if (timer) {
      clearInterval(timer)
      timer = null
    }
    beforeTotalDuration.value = 0
    currentDuration.value = 0
    startTime.value = null
    isRecording.value = false
  }

  return {
    duration: currentDuration,
    formattedDuration,
    isRecording,
    start,
    stop,
    pause,
    resume,
    setStartTime,
    setDuration
  }
}